package com.zang.util;

import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;

/**
 * 密码工具类
 *
 * @author zhaominjian
 * @since 2022/4/2
 */
@Slf4j
public class PasswordUtil {

    // 长度8到20位，包括字母（区分大小写），数字、特殊字符3种以上。
    public static final String REGEX = "^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_]+$)(?![a-z0-9]+$)(?![a-z\\W_]+$)(?![0-9\\W_]+$)[a-zA-Z0-9\\W_]{8,20}$";

    /**
     * 随机密码
     * @return
     */
    public static String randPassword() {

        return RandomUtil.randomString(RandomUtil.BASE_CHAR, 1).toUpperCase() + RandomUtil.randomString(
                RandomUtil.BASE_CHAR, 5) + RandomUtil.randomString(RandomUtil.BASE_NUMBER, 2) + RandomUtil.randomString(
                "!@#$%", 1);

    }

    /**
     * 校验密码
     * @param oriPsw 明文密码
     * @param psw 密文密码
     * @return
     */
    public static boolean match(String oriPsw, String psw) {

        try {
            return md5_32(oriPsw).equals(psw);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 密码加密算法
     * @param plainText 密码明文
     * @return 密码密文
     * @throws Exception 加密算法执行时导致的异常
     */
    public static String md5_32(String plainText) throws Exception {

        String str = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
            str = buf.toString();
        } catch (Exception e) {
            log.error("md5_32=>" + e.getMessage());
        }
        return str;
    }
}
